<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useMainStore } from "@/stores";
import { storeToRefs } from "pinia";
import { PRODUCT_TEMPLATE } from "@/utils/constant/tableColumns";
import ProductInfo from "@/components/product-info.vue";
import { message } from 'ant-design-vue';
import dayjs from "dayjs";
import api from "@/api";
import _ from "lodash";

const stores = useMainStore();
const openTemplate = ref(false);
const tpId = ref(null)
const tabLoading = ref(false)

const table_list = ref([]);

const pageParams = ref({
  page: 1,
  size: 10,
});
const total = ref(0)
const defaultTemp = ref(null) // 默认模板

onMounted(() => {
  getList()
  getDefaultTemplate()
})

const getDefaultTemplate = () => {
  api.getDefaultTemplate().then(res => {
    defaultTemp.value = res.data
  })
}

const saveDefault = (id) => {
  api.saveDefaultTemplate(id).then(res => {
    getDefaultTemplate()
    message.success('默认模板设置成功!');
  })
}

const delTemplate = (id) => {
  api.delTemplate(id).then(res => {
    getList()
  })
}

const getList = () => {
  tabLoading.value = true
  let params = _.cloneDeep(pageParams.value)
  api.getTemplateList(params).then(res => {
    tabLoading.value = false
    table_list.value = res.data.list
    total.value = res.data.total
  }).catch(() => {
    tabLoading.value = false
  })
}


const handleTableChange = (e) => {
  pageParams.value.page = e.current
  getList()
};

const pagination = computed(() => ({
  total: total.value,
  current: pageParams.value.page,
  pageSize: pageParams.value.size,
}));

</script>

<template>
  <div>
    <div class="select-header">
      <a-button type="primary" class="ml-auto" @click="openTemplate = true; tpId = null">新建模板</a-button>
    </div>

    <a-table class="mt-16px" :scroll="{ y: 'calc(100vh - 440px)' }" :columns="PRODUCT_TEMPLATE" :data-source="table_list"
      :pagination="pagination" :loading="tabLoading" @change="handleTableChange">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'createTime'">
          {{ dayjs(record.createTime).format("YYYY/MM/DD HH:mm:ss") }}
        </template>
        <template v-if="column.key === 'operation'">
          <a-button type="link" :disabled="defaultTemp && defaultTemp.id == record.id"
            @click="saveDefault(record.id)">设为默认</a-button>
          <a-button type="link" @click="openTemplate = true; tpId = record.id">修改</a-button>
          <a-popconfirm title="确认要删除该模板吗？" ok-text="确认" cancel-text="取消" @confirm="delTemplate(record.id)">
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
    <ProductInfo v-model:open="openTemplate" :id="tpId"></ProductInfo>
  </div>
</template>
